import { computed, reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { useStorage, StorageSerializers } from '@vueuse/core'
import { Message } from '@/components'
import { FormIndex } from "@types"


const userInfo = useStorage("userInfo", null, undefined, {
    serializer: StorageSerializers.object
})
const token = ref(useStorage("token", "", undefined))

export const useUser = () => {
    const router = useRouter()
    const isRemember=!!userInfo.value

    const loginForm = reactive<FormIndex>({
        username: isRemember?userInfo.value.username:"admin",
        password:isRemember?userInfo.value.password:"",
        remember: isRemember?userInfo.value.remember:false,
    })

    const login = async () => {
        userInfo.value = { id: 1, username: loginForm.username,remember:loginForm.remember,password:loginForm.password }
        token.value = "super",
        router.replace("home")
        Message.success("Login successful!")
    }

    const logout = () => {
        if(!userInfo.value.remember){
            userInfo.value = null
        }
        token.value = ""
        router.replace("login")
    }

    
    const isLogin = computed(() => token.value !== "")

    return {
        loginForm,
        login,
        logout,
        isLogin,
        userInfo
    }
}
